package tq.com.tqteacher.optimize.adapt;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import tq.com.tqteacher.R;
import tq.com.tqteacher.model.TQNewPublish;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.optimize.activity.ActivityOptimizeDetail;

public class AdapterOptimize extends RecyclerView.Adapter {
    private Context mContext;
    public AdapterOptimize(Context pContext){
        mContext = pContext;
    }
    private ArrayList<TQNewPublish> mNewPublishes = new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup pViewGroup, int pI) {
        View lView = LayoutInflater.from(mContext).inflate(R.layout.vh_opitmize_item_layout, pViewGroup, false);
        return new ItemViewHold(lView);
    }

    @Override
    public int getItemCount() {
        return mNewPublishes.size();
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder pViewHolder, int pI) {
        TQNewPublish lPublish = mNewPublishes.get(pI);

        if(pViewHolder instanceof ItemViewHold){
            ((ItemViewHold)pViewHolder).bindData(lPublish);
        }
    }

    public void appendData(ArrayList<TQNewPublish> pNewPublishes){
        int size = mNewPublishes.size();
        mNewPublishes.addAll(pNewPublishes);
        notifyItemRangeInserted(size, pNewPublishes.size());
    }

    public void clear(){
        mNewPublishes.clear();
        notifyDataSetChanged();
    }

    class ItemViewHold extends RecyclerView.ViewHolder{
        private TQNewPublish mNewPublish;
        private TextView mTitle;
        private TextView mCount;

        public ItemViewHold(View pView){
            super(pView);

            pView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TQPublishType.setSharePublishItem(mNewPublish);
                    ActivityOptimizeDetail.show((Activity) mContext);
                }
            });

            mTitle = pView.findViewById(R.id.title);
            mCount = pView.findViewById(R.id.count);
        }

        public void bindData(TQNewPublish pPublish){
            mNewPublish = pPublish;
            if(mNewPublish == null) return;

            mTitle.setText(mNewPublish.getName());
            if(pPublish.getEdit_times() == 0){
                mCount.setVisibility(View.INVISIBLE);
            }else {
                mCount.setText(String.format("已优化%d次", pPublish.getEdit_times()));
                mCount.setVisibility(View.VISIBLE);
            }

            mCount.setVisibility(View.INVISIBLE);
        }
    }
}
